package com.ohuang.launcher;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * 启动页  权限申请  在androidManifest.xml配置
 * 设置授权成功后跳转 <meta-data android:name="launcher_activity" android:value="com.ohuang.launcher.TestActivity"/>
 * 设置授权的权限 多个权限用逗号(,)隔开 <meta-data android:name="permissions" android:value="android.permission.READ_EXTERNAL_STORAGE,android.permission.WRITE_EXTERNAL_STORAGE"/>
 * 授权失败跳转(不设置会直接finish) <meta-data android:name="permissions_fair_launcher_activity" android:value="com.ohuang.launcher.TestActivity"/>
 * 是否开启动态申请权限前自动弹窗提示  <meta-data android:name="permission_interceptor" android:value="true"/>
 */
public class IndexActivity extends Activity {
    public static final String TAG = "IndexActivity";
    private final List<String> permissionList = new ArrayList<>();
    private final List<String> PERMISSIONS = new ArrayList<>();
    private static final int REQUEST_CODE = 7722;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        linearLayout.setGravity(Gravity.CENTER);
        ImageView imageView = new ImageView(this);
        linearLayout.addView(imageView, new ViewGroup.LayoutParams(500, 500));
        try {
            if (getApplicationInfo().icon != 0) {
                imageView.setImageDrawable(getDrawable(getApplicationInfo().icon));
            }
        } catch (Exception ignored) {

        }
        ActivityManager.getInstance().attach(getApplication());
        String permission = getPermission();
        String[] split = permission.split(",");
        for (int i = 0; i < split.length; i++) {
            Log.d(TAG, "onCreate: " + split[i]);
            if (!TextUtils.isEmpty(split[i])) {
                PERMISSIONS.add(split[i]);
            }
        }
        setContentView(linearLayout);
        showDialog();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (REQUEST_CODE == requestCode) {
            boolean GRANTED = true;
            for (int grantResult : grantResults) {
                GRANTED = grantResult == PackageManager.PERMISSION_GRANTED;
                if (!GRANTED) {
                    break;
                }
            }
            if (GRANTED) {
                permissionsSuccess();
            } else {
                permissionsFair();
            }
        }
    }

    public void showDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("注意")//设置对话框的标题
                .setMessage("此应用需获得使用此应用的权限")//设置对话框的内容
                //设置对话框的按钮
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermission();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    private AlertDialog dialog;
    private boolean permissionRequestFair = false;

    @Override
    protected void onResume() {
        super.onResume();
        if (permissionRequestFair) {
            checkPermission();
        }
    }

    public void requestPermission() {
        // 6.0及以上获取没有申请的权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : PERMISSIONS) {
                int checkSelfPermission = checkPermission(permission, Process.myPid(), Process.myUid());
                if (PackageManager.PERMISSION_GRANTED == checkSelfPermission) {
                    continue;
                }
                permissionList.add(permission);
            }
        }
        if (!permissionList.isEmpty()) {
            // 存在未申请的权限则先申请
            requestPermissions( permissionList.toArray(new String[0]), REQUEST_CODE);
        } else {
            permissionsSuccess();
        }
    }
    private void checkPermission() {
        permissionList.clear();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : PERMISSIONS) {
                int checkSelfPermission = checkPermission(permission, Process.myPid(), Process.myUid());
                if (PackageManager.PERMISSION_GRANTED == checkSelfPermission) {
                    continue;
                }
                permissionList.add(permission);
            }
        }
        if (!permissionList.isEmpty()) {
            showWaringDialog();
        } else {
            permissionsSuccess();
            if (dialog != null) {
                dialog.dismiss();
            }
        }
    }

    private void permissionsSuccess() {
        String activityClass = getActivityClass();

        if (!TextUtils.isEmpty(activityClass)) {
            try {

                startActivity(new Intent(IndexActivity.this, Class.forName(activityClass)));
                maybeInterceptorPermission();
            } catch (ClassNotFoundException e) {
                Toast.makeText(IndexActivity.this, "启动失败" + activityClass, Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(IndexActivity.this, "没有配置启动activity", Toast.LENGTH_LONG).show();
        }
        finish();
    }

    private void showWaringDialog() {
        if (dialog != null) {
            dialog.show();
            return;
        }
        dialog = new AlertDialog.Builder(this)
                .setTitle("权限拒绝！")
                .setMessage("请前往设置->应用->权限中打开相关权限，否则功能无法正常运行！")
                .setNegativeButton("取消",(dialog, which)->{

                    String permissions_fair_launcher = getPermissions_fair_launcher();
                    if (!TextUtils.isEmpty(permissions_fair_launcher)) {

                        try {
                            startActivity(new Intent(IndexActivity.this, Class.forName(permissions_fair_launcher)));
                            maybeInterceptorPermission();
                        } catch (ClassNotFoundException e) {
                            Toast.makeText(IndexActivity.this, "启动失败" + permissions_fair_launcher, Toast.LENGTH_LONG).show();
                        }
                    }
                    finish();
                })
                .setPositiveButton("确定", (dialog, which) -> {

                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);

                    intent.setData(uri);
                    startActivity(intent);
                })
                .setCancelable(false)
                .show();
    }

    private void permissionsFair() {
        permissionRequestFair = true;
        showWaringDialog();
    }


    public String getActivityClass() {
        ActivityInfo ai = null;
        try {
            ai = this.getPackageManager().getActivityInfo(new ComponentName(this, IndexActivity.class), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String data = ai.metaData.getString("launcher_activity");
        return data;
    }
    //多权限逗号隔开
    public String getPermission() {
        ActivityInfo ai = null;
        try {
            ai = this.getPackageManager().getActivityInfo(new ComponentName(this, IndexActivity.class), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String data = ai.metaData.getString("permissions");
        return data;
    }
    public String getPermissions_fair_launcher() {
        ActivityInfo ai = null;
        try {
            ai = this.getPackageManager().getActivityInfo(new ComponentName(this, IndexActivity.class), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String data = ai.metaData.getString("permissions_fair_launcher_activity");
        return data;
    }

    public boolean getPermission_interceptor() {
        ActivityInfo ai = null;
        try {
            ai = this.getPackageManager().getActivityInfo(new ComponentName(this, IndexActivity.class), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        boolean data = ai.metaData.getBoolean("permission_interceptor",false);
        return data;
    }

    public void maybeInterceptorPermission(){
        boolean permission_interceptor = getPermission_interceptor();
        if (permission_interceptor){
            PermissionInterceptor.hook();
        }
    }




    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
